package src;
/**
 * The Subtraction class, in which implement the Expression Interface
 * represents the Subtraction Expression (i.e., a-b, where a and b are expressions as well)
 * A subtraction expression can be evaluated, derived and return its last operation symbol.
 *
 * @author Intro111 Staff
 */

public class Subtraction implements Expression {

    private Expression first, second;


    /**
     * Constructor that creates subtraction expression composed of the two expressions
     *
     * @param first  the first expression
     * @param second the second expression
     * @throws RunTimeException for null input expressions
     */
    public Subtraction(Expression first, Expression second) {
        if ((first == null) || (second == null)) {
            throw new RuntimeException("Subtraction constructor got a null argument.");
        }
        this.first = first;
        this.second = second;
    }

    /**
     * Returns the last operation symbol of subtraction expression
     *
     * @return String "-" that represents the last operation
     */
    public String getLastOperationSymbol() {
        return "-";
    }

    /**
     * Evaluate the subtraction expression
     *
     * @return double that represents the evaluation of the subtraction expression
     */
    public double evaluate() {
        return first.evaluate() - second.evaluate();
    }

    /**
     * Derives the subtraction expression by a variable.
     *
     * @param var the variable to derive by
     * @return the derived expression by param var
     * @throws RunTimeException for a null var
     */

    public Expression derivative(Variable var) {
        if (var == null) {
            throw new RuntimeException("Subtraction derivative(Variable var) got a null argument.");
        }

        return new Subtraction(first.derivative(var),
                second.derivative(var));
    }

    /**
     * Compares this subtraction expression to the specified object.
     * The result is true if and only if the argument is not null, the argument is instance of Subtraction expression and the sub-expressions are equals.
     *
     * @param other The object to compare this expression against
     * @return true if the given object represents an expression equivalent to this expression, false otherwise
     */
    public boolean equals(Object other) {
        return ((other instanceof Subtraction) &&
                (first.equals(((Subtraction) other).first)) &&
                (second.equals(((Subtraction) other).second)));
    }

    /**
     * Returns a string representing the Subtraction Expression.
     *
     * @return String that represents the Subtraction Expression
     */
    public String toString() {
        return "(" + first.toString() + getLastOperationSymbol() + second.toString() + ")";
    }
}
